package com.ruoyi.common.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * 对称加密AES算法 工具类
 *
 * @Author wangyang
 * @Version
 **/
public class AesUtils {
    public static final String ALGORITHM = "AES";
    public static final String AES_ECB_PKCS5PADDING = "AES/ECB/PKCS5Padding";
    public static final String AES_ECB_NOPADDING = "AES/ECB/NoPadding";
    public static final String AES_CBC_NOPADDING = "AES/CBC/NoPadding";
    public static final String AES_CBC_PKCS5PADDING = "AES/CBC/PKCS5Padding";
    private final static String SECRET = "mgjr0123dhjy!@#$";
    private final static String CHARSET = "UTF8";

    /**
     * 生成128位随机密钥
     */
    public static byte[] randomKey() {
        return randomKey(128);
    }

    /**
     * 生成随机密钥
     *
     * @param keySize 密钥位数
     */
    private static byte[] randomKey(int keySize) {
        if (keySize != 128) {
            throw new RuntimeException("AES密钥长度不合法. keySize:" + keySize);
        }
        KeyGenerator kg = null;
        try {
            kg = KeyGenerator.getInstance(ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        kg.init(keySize, new SecureRandom());
        byte[] key = kg.generateKey().getEncoded();
        return key;
    }

    /**
     * 加密数据
     *
     * @param data 待加密数据
     * @param key  密钥
     */
    public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        if (key.length != 16) {
            throw new RuntimeException("AES加密失败, 密钥不是128位");
        }
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        return cipher.doFinal(data);
    }

    /**
     * 解密数据
     *
     * @param value 待解密数据
     * @param key   密钥
     */
    public static byte[] decrypt(byte[] value, byte[] key) throws Exception {
        if (key.length != 16) {
            throw new RuntimeException("AES解密失败, 密钥不是128位");
        }
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        return cipher.doFinal(value);
    }


    /**
     * 默认的AES加密字符串方法，可以内部使用
     * 对明文的UTF-8编码字节进行加密，然后使用Base64转码
     * 密钥使用UTF-8编码
     *
     * @param data 明文
     * @param key  加密密钥
     */
    public static String encrypt(String data, String key) throws Exception {
        if (StringUtils.isBlank(data) || StringUtils.isBlank(key)) {
            throw new RuntimeException("AES加密失败, 参数有误. data: " + data + ", key: " + key);
        }
        byte[] keyBytes = key.getBytes(CHARSET);
        byte[] dataBytes = data.getBytes(CHARSET);
        byte[] encryptBytes = encrypt(dataBytes, keyBytes);
        return new String(Base64.encodeBase64(encryptBytes));
    }

    /**
     * 默认的AES解密字符串方法，可以内部使用
     * 对密文使用Base64转码后，再进行解密，然后再转为UTF-8编码
     * 密钥使用UTF-8编码
     *
     * @param ciphertext 密文
     * @param key        加密密钥
     */
    public static String decrypt(String ciphertext, String key) throws Exception {
        if (StringUtils.isBlank(ciphertext) || StringUtils.isBlank(key)) {
            throw new RuntimeException("AES解密失败, 参数有误. ciphertext: " + ciphertext + ", key: " + key);
        }
        byte[] keyBytes = key.getBytes(CHARSET);
        byte[] dataBytes = Base64.decodeBase64(ciphertext);
        byte[] keyBytesDecrypt = decrypt(dataBytes, keyBytes);
        return new String(keyBytesDecrypt, CHARSET);
    }

    /**
     * 解密数据
     *
     * @param value 待解密数据
     * @param key   密钥
     */
    public static byte[] decryptHex(byte[] value, byte[] key) throws Exception {
        if (key.length != 16) {
            throw new RuntimeException("AES解密失败, 密钥不是128位");
        }
        Cipher cipher = Cipher.getInstance(ALGORITHM);//AES_ECB_NOPADDING
        SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        return cipher.doFinal(value);
    }

    public static String encrypt(String data) throws Exception {
        return encrypt(data, SECRET);
    }

    public static String decrypt(String data) throws Exception {
        return decrypt(data, SECRET);
    }

    public static String encryptHex(String data, String key) throws Exception {
        return parseByte2HexStr(encrypt(data.getBytes("utf-8"), key.getBytes()));
    }

    public static String decryptHex(String data, String key) throws Exception {
        return new String(decryptHex(parseHexStr2Byte(data), key.getBytes()), "utf-8");
    }



    /**
     * 加密 AES/ECB/PKCS5Padding
     *
     * @param data 明文
     * @param key  密钥
     * @return 密文
     */
    public static String encryptPKCS5Padding(String data, String key) throws Exception {
        if (key.length() != 16) {
            throw new RuntimeException("AES加密失败, 密钥不是128位");
        }
        if (StringUtils.isBlank(data) || StringUtils.isBlank(key)) {
            throw new RuntimeException("AES加密失败, 参数有误. data: " + data + ", key: " + key);
        }
        byte[] keyBytes = key.getBytes(CHARSET);
        byte[] dataBytes = data.getBytes(CHARSET);
        Cipher cipher = Cipher.getInstance(AES_ECB_PKCS5PADDING);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        return new String(Base64.encodeBase64(cipher.doFinal(dataBytes)));
    }

    /**
     * 解密 AES/ECB/PKCS5Padding
     * @param data 密文
     * @param key  密钥
     * @return 明文
     */
    public static String decryptPKCS5Padding(String data, String key) throws Exception {
        if (StringUtils.isBlank(data) || StringUtils.isBlank(key)) {
            throw new RuntimeException("AES解密失败, 参数有误. ciphertext: " + data + ", key: " + key);
        }
        byte[] keyBytes = key.getBytes(CHARSET);
        byte[] dataBytes = Base64.decodeBase64(data);
        if (keyBytes.length != 16) {
            throw new RuntimeException("AES解密失败, 密钥不是128位");
        }
        Cipher cipher = Cipher.getInstance(AES_ECB_PKCS5PADDING);
        SecretKey keySpec = new SecretKeySpec(keyBytes, ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        return new String(cipher.doFinal(dataBytes), CHARSET);
    }


    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
                    16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * AES加密 AES_CBC_PKCS5PADDING
     * @param content 明文
     * @param KEY 秘钥key
     * @param IV 偏移量iv
     * @return
     */
    public static String encrypt(String content, String KEY, String IV) {
        try {
            byte[] raw = KEY.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            //"算法/模式/补码⽅式"
            Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5PADDING);
            //使⽤CBC模式，需要⼀个向量iv，可增加加密算法的强度
            IvParameterSpec ips = new IvParameterSpec(IV.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ips);
            byte[] encrypted = cipher.doFinal(content.getBytes());
            return new BASE64Encoder().encode(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * AES解密 AES_CBC_PKCS5PADDING
     * @param content 密文
     * @param KEY 秘钥key
     * @param IV 偏移量iv
     * @return
     */
    public static String decrypt(String content, String KEY, String IV) {
        try {
            byte[] raw = KEY.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5PADDING);
            IvParameterSpec ips = new IvParameterSpec(IV.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, ips);
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(content);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * AES加密 AES_CBC_NOPADDING
     * @param data 明文
     * @param KEY 秘钥key
     * @param IV 偏移量iv
     * @return
     */
    public static String encryptCBCNoPadding(String data, String KEY, String IV) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = data.getBytes();
            int dataLength = dataBytes.length;
            if (dataLength % blockSize != 0) {
                dataLength = dataLength + (blockSize - (dataLength % blockSize));
            }
            byte[] plaintext = new byte[dataLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), "AES");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
            byte[] bytes = cipher.doFinal(plaintext);
            return Base64.encodeBase64String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * AES解密 decryptCBCNoPadding
     * @param content 密文
     * @param KEY 秘钥key
     * @param IV 偏移量iv
     * @return
     */
    public static String decryptCBCNoPadding(String content, String KEY, String IV) {
        try {
            byte[] raw = KEY.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance(AES_CBC_NOPADDING);
            IvParameterSpec ips = new IvParameterSpec(IV.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, ips);
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(content);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static final String AES_CBC_CIPHER = "AES/CBC/PKCS5Padding";
    /**
     * AES 加密 CBC模式
     *
     * @param data 需要加密的内容
     * @param key  密钥
     * @return 密文
     */
    public static String encryptHyq(String data, String key) {
        byte[] dataByteArray = data.getBytes(StandardCharsets.UTF_8);
        byte[] keyByteArray = java.util.Base64.getDecoder().decode(key);
        try {
            SecretKeySpec secretKey = new SecretKeySpec(keyByteArray, "AES");
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance(AES_CBC_CIPHER);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(keyByteArray));
            byte[] valueByte = cipher.doFinal(dataByteArray);
            return java.util.Base64.getEncoder().encodeToString(valueByte);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * AES 解密 CBC模式
     *
     * @param data 待解密内容 base64 字符串
     * @param key  密钥
     * @return 明文
     */
    public static String decryptHyq(String data, String key) {
        byte[] originalData = java.util.Base64.getDecoder().decode(data.getBytes());
        byte[] keyByteArray = java.util.Base64.getDecoder().decode(key);
        try {
            SecretKeySpec secretKey = new SecretKeySpec(keyByteArray, "AES");
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance(AES_CBC_CIPHER);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(keyByteArray));
            byte[] valueByte = cipher.doFinal(originalData);
            return new String(valueByte,StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws Exception {
        /*String mobile = AesUtils.decrypt("iyZKJdWaAtj0pGgcr8X5hw==", new StringBuilder("14d493d7e65000f6").reverse().toString());
        System.out.println(mobile);**/
        /*String data = encrypt("{\"phone\":\"19927413881\",\"channel_source\":\"chlrpqb\"}", "mgjr0123dhjy!@#$");
        Map<String, Object> map = new HashMap<>();

        map.put("data",data);
        JSONObject obj = HttpPostUtils.postJSON("https://api.shlyxxjs.com/api/yhzd/deleteCust", map);
        System.out.println(obj);*/
        //String s = encrypt("19927413", "EB335P5VR93QN46B", "C235E0BEM01Z7B33");
        //System.out.println("test加密后：" + s);
//        System.out.println(decrypt("xNDCsvSDiiG6mbjnACYNi2P/A4nKX1tMCHn6fTlaA2+Cho6ZyF6otzIaSQFEsKbTol9JAhHmL2SG4N9TxVjB8Q==","nYKL5dyLbZHVSJ2V","WGcv9U76fXGUfkd3"));
        //System.out.println(s + "解密后：" + decrypt("a8od/eygNiCuFstQH124stsIY/SCNP/Kz4IDJtKtXefrOgsnVz4dxF4eB1mipDEH+sRDkp8OuxaatqHKeficF29fotluygldl1g/zeU1065DW/lr433BUzcwhtdr0J0AoADYAX4oqlgqOezC+2RQEpW1N0elaKRWbGnHuBqk6WI98UfPMa2M3zcAS3G/BhewJKZ1Q3QctRNJBTzh7m1fm71kBqXxrmb3Lv4dQfIVXogm3SuU6ho/o/qkjBLb0mr/3Dz5628PwHaVGq61d6Nb2lOjY3Xxg4F5fsD4UXuhsC1sEieIuWWZ+j4I8DXxsZ2aha2mmAmiYQXo97FtIYrKcw==", "EB335P5VR93QN46B", "C235E0BEM01Z7B33"));
        //System.out.println(Md5Util.md5("chl013"+"0v9xzvYcr112TREt9yiJjQ=="+"13333"+"EB335P5VR93QN46B"));
        //String data = "{\"phone\":\"19927413881\",\"channelCode\":\"chl013\",\"realName\":\"测试\",\"price\":50000,\"city\":\"上海\"}";
        //System.out.println(encrypt(data, "EB335P5VR93QN46B", "C235E0BEM01Z7B33"));
//        System.out.println(decryptPKCS5Padding("mQjJeYEvfWeenbMYO7nlUaLmZruGTSsha4HeiZW3YGIsraBT7dbLWXFfu1vVkK3KsA8jQjWeppze++rCTiqLDYFpd+0wRxZoVm+HkcNDfuCJigJ5yesZztEO7AKixap0PkGHsCoD0tYUaCHhF1vkqLgit1geh15wSdLT50Q1L0izyFkSril3xPa8Eo7foCYBz9SX2ByRF0dCyLCv+6y4oJDFmLoL6zCG6tfhZYP6jn/6M/dx+oa7duTtFEa2WL75nNF6no1ALtNZrBNXg1Mkgv5xMmH1zsDkL0jf27mwsVbNL9+dGtCCWGXGLGlG9NJsBIhGvFUlLUipDwrOp2GhAAS0Q37R0Z3jQvYbAL4vzEE3sZVYfY+36Wa/2lkQv7j7wPFZSGU6hiQE60napv1hmnX98xWpJckDpho4femU5HPbpRuwQzbvDzPdvELnfNqE","r6D1H0XZQc0l1wJ58qzTlw=="));



        System.out.println(decryptCBCNoPadding("mmwpec7jOXOV2By2W5+clw==","EB335P5VR93QN46B", "C235E0BEM01Z7B3A"));
        String data="{\"age\":40,\"applyLimit\":2,\"carProperty\":2,\"creditInvestigation\":0,\"gender\":1,\"houseProperty\":0,\"housingFund\":2,\"identity\":\"350583198408230075\",\"insurance\":2,\"job\":10,\"mobile\":\"16000057085\",\"payoffForm\":2,\"realName\":\"测试\",\"sesameCredit\":2,\"socialSecurity\":2,\"workCity\":\"天津市,市辖区\",\"workCityCode\":\"120000,120100\"}";
        System.out.println(encryptHyq(data, "r6D1H0XZQc0l1wJ58qzTlw=="));
        data ="F1LlhUB/lsDrpTp4spSsO+OzaUtoKtFEqos/K9D16NXJ7kqFpK05AvpOZ2d3lJxPCIMxq7AhaAXd9bxyeiOt1pSA6J1DPU0J1rsoa6n2zqNv+e/e/NUpVtdvD+3jx9mkbjr0hhHlIjGZCY6LmURWL7hZpajhMbgBRjZ7OpOR1ronx0fkT54NzCFJfY7ThglD3t/PNl88dXH7P6CbxjwX6p0wYn4LcVj7ub45X4KSmfyniNskIvhjV7mCLxhJOn744q9Of3PqZbvXxq47Cl7ibIJuV2l2PV2p0R5aXmQFyplmFmK9+DIp4Kjod8g6Y9/uWr9/Q1B3n4t+W/pAUK0vrJ0D7KeTDOAVqb7CK3c1xASDApMNs7PIBEgSY2YHeq1WyrnL2gfQ4CNqKOuVNWBfneWN/2uH4A8L9rZiga3Vdb0K1qY78h69gYiaCh+FQeRRfQdct17WEUa4aaycjn4V3xojVb1pYNbwaFn8s5iQzq0=";
        System.out.println(decryptHyq(data, "r6D1H0XZQc0l1wJ58qzTlw=="));
        System.out.println(encrypt("admin!@#123"));
        System.out.println(decrypt("bHLNvVWmrbcy+wfzx4V/rw=="));


    }

}
